﻿using UnityEngine;
using System.Collections;
using UniLua;
using TCG;

namespace TCG.FFI
{
	public static class FFIToolsLib 
	{
		public static string LIB_NAME = "FFIToolsLib";

		/// <summary>
		/// <para>用于在lua中做强制类型转换，不会做安全检查，只是换一下metatable。目标类型必须是已经
		/// 注册过的导出类型。</para>
		/// <para>用法：result = lua_tools_lib.static_cast (src_object, "target_lib_name"); </para>
		/// </summary>
		public static int lf_StaticCast (ILuaState luaState)
		{
			object userdata = luaState.ToUserData (1);
			string targetLibName = luaState.ToString (2);
			LuaTools.L_PushUserData (luaState, userdata, targetLibName);
			return 1;
		}
		
		/// <summary>
		/// 获取指定类型并返回，用法：obj_type = lua_tools_lib.type_of ("some_class_name");
		/// </summary>
		public static int lf_TypeOf (ILuaState luaState)
		{
			string classFullName = luaState.ToString (1);
			System.Type t = System.Type.GetType (classFullName);
			luaState.PushUserData (t);
			return 1;
		}

		/// <summary>
		/// <para>暴露luaL_ref方法给lua。</para>
		/// <para>用法：ref_id = lua_tools_lib.lua_ref (src_object) </para>
		/// </summary>
		public static int lf_LuaLRef (ILuaState luaState)
		{
			int refId = luaState.L_Ref (LuaDef.LUA_REGISTRYINDEX);
			luaState.PushInteger (refId);
			return 1;
		}

		/// <summary>
		/// <para>暴露luaL_unref方法给lua</para>
		/// <para>用法：lua_tools_lib.lua_unref (ref_id) </para>
		/// </summary>
		public static int lf_LuaLUnref (ILuaState luaState)
		{
			int refId = luaState.L_CheckInteger (-1);
			luaState.L_Unref (LuaDef.LUA_REGISTRYINDEX, refId);
			return 0;
		}

		/// <summary>
		/// <para>暴露luaL_stackTrace方法给lua</para>.
		/// </summary>

		public static int lf_LuaLStackTrace (ILuaState luaState)
		{
			string message = null;
			if (luaState.GetTop () == 1)
			{
				message = luaState.ToString (-1);
			}
			luaState.L_Traceback (luaState, message, 1);
			return 1;
		}
	}
}
